<template>
  <t-modal
    title="通知"
    width="1248px"
    :visible="visible"
    @cancel="closeModal()"
    @ok="onSubmit()"
    wrapClassName="add-modal-container"
    v-bind="footer"
    forceRender
    :confirmLoading="submitLoading"
  >
    <div class="curve-modal-body">
      <a-form-model ref="ruleForm" :model="form" :rules="rules">
        <a-form-model-item
          label="通知人员"
          prop="userNameIds"
          :rules="{
            required: true,
            message: '请选择通知人员',
          }"
        >
          <div class="people-container">
            <div class="left-warp">
              <a-input-search
                placeholder="请输入关键字"
                style="width: 100%"
                @search="onSearch($event)"
                v-model="keyWord"
                allow-clear
              />
              <div class="tree-container">
                <a-tree
                  v-model="checkedKeys"
                  checkable
                  show-icon
                  :expanded-keys="expandedKeys"
                  :auto-expand-parent="autoExpandParent"
                  :selected-keys="selectedKeys"
                  :tree-data="peopleSource"
                  :replaceFields="{
                    children: 'children',
                    title: 'text',
                    key: 'uuid',
                    value: 'uuid',
                  }"
                  @expand="onExpand"
                  @select="onSelect"
                  @check="onCheck"
                >
                  <!-- 自定义图标 -->
                  <template slot="custom" slot-scope="{ isOrg }">
                    <icon-fonts v-if="isOrg" icon="icon-jiagou"></icon-fonts>
                    <span v-else class="user-icon">
                      <icon-fonts icon="icon-renyuan" />
                    </span>
                  </template>
                  <template slot="title" slot-scope="{ text }">
                    <div class="custom-tree-title-warp">
                      <div class="title" :title="text">
                        {{ text }}
                      </div>
                    </div>
                  </template>
                </a-tree>
              </div>
            </div>
            <div class="right-warp">
              <div class="statistics-header">
                已选：{{ selectPeople.length }}人
                <div class="reset" @click="handleRest()">清空</div>
              </div>
              <div class="statistics-body">
                <a-empty v-if="selectPeople.length == 0" :description="false" />
                <a-row :gutter="[8, 8]" v-else>
                  <a-col
                    :span="12"
                    v-for="(item, index) in selectPeople"
                    :key="index"
                  >
                    <div class="people-item">
                      <div class="name">
                        <div class="icon">
                          <icon-fonts icon="icon-renyuan" />
                        </div>
                        <div class="user">{{ item.text }}</div>
                      </div>
                      <div class="close" @click="deletePeole(item, index)">
                        <a-icon type="close" />
                      </div>
                    </div>
                  </a-col>
                </a-row>
              </div>
            </div>
          </div>
        </a-form-model-item>
        <a-form-model-item label="通知内容" prop="content">
          <a-textarea placeholder="请输入" :rows="3" v-model="form.content" />
        </a-form-model-item>
      </a-form-model>
      <div class="sub-title">历史记录</div>
      <vxe-table
        ref="xTable"
        align="left"
        show-overflow
        show-header-overflow
        border="default"
        :data="tableData"
        :column-config="{ resizable: true }"
        size="small"
        :loading="loading"
        height="200px"
      >
        <vxe-column
          type="seq"
          width="80"
          title="序号"
          fixed="left"
        ></vxe-column>
        <vxe-column field="orgName" title="单位名称"> </vxe-column>
        <vxe-column field="content" title="通知内容"> </vxe-column>
        <vxe-column field="read" title="已读"> </vxe-column>
        <vxe-column field="unRead" title="未读"> </vxe-column>
        <vxe-column field="sendTime" title="通知时间"> </vxe-column>
      </vxe-table>
    </div>
  </t-modal>
</template>

<script>
import cloneDeep from "lodash.clonedeep";
import { mapGetters } from "vuex";
import { axios } from "@/utils/request";
import { getToken, downloadDfs } from "@/utils/TopVUI";
import { addAttributeByKey, flatTreeData } from "@/utils/util.js";

export default {
  components: {},
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    parameter: {
      type: Object,
      default() {
        return {};
      },
    },
    versionInfo: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  data() {
    return {
      type: "SCHEDULE_VERSION",
      footer: {},
      submitLoading: false,
      //关键字
      keyWord: "",
      form: {
        //通知人员
        userNameIds: [],
        //通知内容
        content: "",
      },
      rules: {
        content: [
          {
            required: true,
            message: "请输入通知内容",
          },
        ],
      },
      //人员
      peopleSource: [],
      expandedKeys: [],
      autoExpandParent: true,
      selectedKeys: [],
      currentTreeNode: {},
      checkedKeys: [],
      cloneTreeData: [],
      //选择的人员
      selectPeople: [],
      //
      tableData: [],
      loading: false,
    };
  },
  computed: {
    ...mapGetters(["configData"]),
    menuName() {
      let { title } = this.$route.meta;
      return title;
    },
  },
  watch: {
    visible: {
      handler(val) {
        if (val) {
          this.getData();
        }
      },
      immediate: true,
    },
  },

  methods: {
    getData() {
      this.getPeopleData();
      this.getTableData();
      let { name, code, originalTypeDesc } = this.versionInfo;
      this.form.content = `【${originalTypeDesc}】，最新版本【${name}】,版本号【${code}】已发布，请及时查看！`;
    },

    //查询参会人员
    getPeopleData() {
      return new Promise((resolve, reject) => {
        axios
          .post(
            `/mdata/organization/getTreeProAndUserData`,
            {},
            {
              headers: {
                "Content-Type": "application/json;charset=UTF-8",
              },
            }
          )
          .then((res) => {
            this.cloneTreeData = cloneDeep(res?.data ?? []);
            // let flatData = flatTreeData(this.cloneTreeData, "children");
            // this.expandedKeys = flatData.map((v) => v.value).filter((v) => v);
            let filterData = addAttributeByKey(
              null,
              "scopedSlots",
              { icon: "custom" },
              this.cloneTreeData,
              "children"
            );
            this.peopleSource = filterData ?? [];
            this.recursiveTree(this.peopleSource);
            resolve();
          })
          .catch((_) => {
            this.peopleSource = [];
            reject();
          })
          .finally((_) => {});
      });
    },
    //处理角色树
    recursiveTree(data = []) {
      data.forEach((item) => {
        this.$set(item, "disabled", true);
        if (item.orgName) {
          item.text = item.orgName;
          item.uuid = item.id;
        }
        if (item.children && item.children.length > 0) {
          this.recursiveTree(item.children);
        }
        if (item.list && item.list.length > 0) {
          let array = [];
          item.list.forEach((v) => {
            array.push({
              text: v.userName,
              uuid: v.userNameId,
              disabled: false,
            });
          });
          item.children = item.children.concat(array);
        }
      });
    },

    //查询历史记录
    getTableData() {
      this.loading = true;
      return new Promise((resolve, reject) => {
        let { parameter, type } = this;
        axios
          .post(
            `/message/msgWebNotice/getNoticeList`,
            {
              type: parameter.pushType,
              puuid: parameter.originalId,
            },
            {
              headers: {
                "Content-Type": "application/json;charset=UTF-8",
              },
            }
          )
          .then((res) => {
            let { statusCode } = res;
            if (statusCode == 200) {
              this.tableData = res;
            } else {
              this.tableData = [];
            }
            // this.tableData = res ?? [];
            resolve();
          })
          .catch((_) => {
            console.log(this.tableData, " this.tableData");
            this.tableData = [];
            reject();
          })
          .finally((_) => {
            this.loading = false;
          });
      });
    },

    //监听树形选择
    onSelect(selectedKeys, info) {
      let { uuid } = info.node.dataRef;
      this.currentTreeNode = info.node.dataRef;
      this.selectedKeys = [uuid];
    },
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },

    onCheck(checkedKeys, info) {
      let { node, checked } = info;
      let { dataRef } = node;
      let row = {
        text: dataRef.text,
        uuid: dataRef.uuid,
      };
      if (checked) {
        this.selectPeople.push(row);
        this.selectPeople = this.uniqueBy(this.selectPeople, "uuid");
      } else {
        this.selectPeople = this.selectPeople.filter((v) => row.uuid != v.uuid);
      }
      this.checkedKeys = this.selectPeople.map((v) => v.uuid);
      this.form.userNameIds = this.selectPeople;
      this.$refs["ruleForm"].clearValidate(["userNameIds"]);
    },

    //json数组去重
    uniqueBy(arr, key) {
      const unique = {};
      return arr.filter((item) => {
        if (!unique[item[key]]) {
          unique[item[key]] = true;
          return true;
        }
        return false;
      });
    },
    handleRest() {
      this.form.userNameIds = [];
      this.selectPeople = [];
      this.checkedKeys = [];
    },
    //删除已选择的人员
    deletePeole(item, index) {
      this.selectPeople.splice(index, 1);
      this.form.userNameIds = this.selectPeople;
      this.$refs["ruleForm"].clearValidate(["userNameIds"]);

      //当前删除人员的父节点处
      let parentNode = "";
      this.peopleSource.map((v) => {
        if (v.children) {
          v.children.map((e) => {
            if (e.uuid == item.uuid) {
              parentNode = v;
            }
          });
        }
      });

      if (parentNode) {
        this.checkedKeys = this.checkedKeys.filter(
          (v) => item.uuid != v && v != parentNode.uuid
        );
      } else {
        this.checkedKeys = this.checkedKeys.filter((v) => item.uuid != v);
      }
    },

    onSubmit() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          let { form, type, parameter } = this;
          let { uuid, typeDesc, originalId } = this.versionInfo;
          let uuids = form.userNameIds.map((v) => v.uuid);
          let formJson = {
            //数据id
            puuid: originalId,
            //菜单名称
            title: `【${typeDesc}】新版本通知`,
            //通知类型
            type: parameter.pushType,
            //通知内容
            content: form.content,
            //通知人员
            userNameIds: uuids.toString(),
            url: ``,
          };
          this.submitLoading = true;
          axios
            .post(`/probusiness/notice/addNotice`, formJson, {
              headers: {
                "Content-Type": "application/json",
              },
            })
            .then((res) => {
              if (res.statusCode === 200 || res === 1) {
                this.$message.success("通知成功", 1.5);
                this.$parent.getTableData();
                this.closeModal();
              } else {
                this.$message.error(res?.message ?? "通知失败");
              }
            })
            .catch((_) => {
              this.$message.error(_?.message ?? "通知失败");
            })
            .finally((_) => {
              this.submitLoading = false;
            });
        }
      });
    },

    //重置表单
    resetForm() {
      this.keyWord = "";
      //人员
      this.peopleSource = [];
      this.expandedKeys = [];
      this.autoExpandParent = true;
      this.selectedKeys = [];
      this.currentTreeNode = {};
      this.checkedKeys = [];
      this.cloneTreeData = [];
      //选择的人员
      this.selectPeople = [];
      this.form = {
        //通知人员
        userNameIds: [],
        //通知内容
        content: "",
      };
      this.$refs.ruleForm.resetFields();
    },

    //关闭
    closeModal() {
      this.resetForm();
      this.$emit("update:visible", false);
    },

    onSearch() {
      let { keyWord, cloneTreeData } = this;
      let cloneData = cloneDeep(cloneTreeData);
      this.peopleSource = this.filterTree(cloneData, "children", (node) =>
        node.text.includes(keyWord)
      );
    },

    //过滤树形数据
    filterTree(data, children = "children", filterFunc) {
      return data
        .filter((node) => {
          // 如果当前节点符合条件，直接返回true
          if (filterFunc(node)) {
            return true;
          }
          // 如果当前节点有子节点，递归过滤子节点
          if (node[children]) {
            node[children] = this.filterTree(
              node[children],
              children,
              filterFunc
            );
            // 如果过滤后的子节点不为空，说明当前节点需要保留
            return node[children].length > 0;
          }
          // 当前节点不符合条件，也没有子节点或子节点不符合条件，返回false
          return false;
        })
        .map((node) => {
          // 创建新对象，避免修改原始数据
          return {
            ...node,
            [children]: node[children]
              ? this.filterTree(node[children], children, filterFunc)
              : [],
          };
        });
    },
  },
};
</script>

<style lang="less" scoped>
/deep/.add-modal-container {
  .ant-modal-body {
    padding: 0 !important;
    .curve-modal-body {
      box-sizing: border-box;
      padding: 14px 70px 14px 40px;
      height: 700px;
      overflow: auto;
      .ant-form-item {
        display: flex;
        .ant-form-item-label {
          flex-shrink: 0;
          width: 140px;
          label {
            color: #333333;
          }
        }
        .ant-form-item-control-wrapper {
          flex: 1;
          overflow: hidden;
        }
      }
      .people-container {
        height: 334px;
        background: #ffffff;
        border-radius: 4px;
        border: 1px solid #d4d7d8;
        display: flex;
        overflow: hidden;
        .left-warp {
          flex: 1;
          border-right: 1px solid #d4d7d8;
          display: flex;
          flex-direction: column;
          padding: 10px 16px;
          box-sizing: border-box;
          overflow: hidden;
          .ant-input-affix-wrapper .ant-input {
            border-color: #d9d9d9;
          }

          .tree-container {
            flex: 1;
            overflow: auto;
            overflow-x: hidden;
            .ant-tree {
              .ant-tree-node-content-wrapper {
                &:hover {
                  .operate {
                    .anticon {
                      display: inline-block !important;
                    }
                  }
                }
              }
              li {
                width: 100%;
                .ant-tree-node-content-wrapper {
                  position: relative;
                  width: calc(100% - 46px);
                  padding: 0;
                  .ant-tree-iconEle {
                    color: #1677ff;
                    font-size: 16px;
                  }
                  .user-icon {
                    display: inline-block;
                    width: 16px;
                    height: 16px;
                    background: #d9d9d9;
                    border-radius: 4px 4px 4px 4px;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    position: relative;
                    top: 4px;
                    .anticon {
                      color: #ffffff;
                      font-size: 12px;
                    }
                  }

                  .ant-tree-title {
                    overflow: hidden;
                    display: inline-block;
                    width: calc(100% - 26px);
                    .custom-tree-title-warp {
                      display: flex;
                      width: 100%;
                      .title {
                        flex: 1;
                        overflow: hidden;
                        overflow: hidden;
                        white-space: nowrap;
                        text-overflow: ellipsis;
                      }
                      .operate {
                        flex-shrink: 0;
                        color: #8c8c8c;
                        .anticon {
                          display: none;
                          margin-right: 8px;
                          &:last-of-type {
                            margin-right: 0;
                          }
                        }
                        .add-file-button {
                          font-size: 15px;
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
        .right-warp {
          flex: 1;
          display: flex;
          flex-direction: column;
          padding: 10px 0;
          box-sizing: border-box;
          overflow: hidden;
          .statistics-header {
            padding: 0 16px;
            box-sizing: border-box;
            display: flex;
            justify-content: space-between;
            line-height: 32px;
            font-size: 14px;
            color: #333333;
            .reset {
              color: #1890ff;
              cursor: pointer;
            }
          }
          .statistics-body {
            padding: 0 16px;
            box-sizing: border-box;
            flex: 1;
            overflow: auto;
            overflow-x: hidden;
            position: relative;
            .people-item {
              height: 32px;
              background: #f7f7f7;
              display: flex;
              align-items: center;
              justify-content: space-between;
              padding: 0 10px;
              box-sizing: border-box;
              .name {
                display: flex;
                align-items: center;
                .icon {
                  width: 16px;
                  height: 16px;
                  background: #d9d9d9;
                  border-radius: 4px 4px 4px 4px;
                  margin-right: 10px;
                  display: flex;
                  align-items: center;
                  justify-content: center;
                  .anticon {
                    color: #ffffff;
                    font-size: 12px;
                  }
                }
                .user {
                  flex: 1;
                  font-size: 14px;
                  color: #333333;
                  overflow: hidden;
                  text-overflow: ellipsis;
                  white-space: nowrap;
                }
              }
              .close {
                cursor: pointer;
              }
            }
            .ant-empty {
              position: absolute;
              left: 50%;
              top: 50%;
              transform: translate(-50%, -50%);
            }
          }
        }
      }
      .sub-title {
        padding-left: 16px;
        font-family: Microsoft YaHei;
        font-weight: 400;
        font-size: 18px;
        color: #525a5d;
        position: relative;
        margin-bottom: 10px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        &::after {
          content: "";
          width: 3px;
          height: 16px;
          background: #1890ff;
          position: absolute;
          left: 0;
          top: 50%;
          transform: translateY(-50%);
        }
        .ant-btn {
          margin-right: 0;
        }
      }
    }
  }
}
</style>
